import { createRouter, createWebHashHistory } from "vue-router";
import config from '@/config'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { type App } from 'vue'
import tool from '../utils/tool.js';
import request from '../utils/requestLogin.js'
import systemRouter from '../router/system_router';
import { extendRouter } from '../utils/auth'

// 创建路由实例
const router = createRouter({
    history: createWebHashHistory(config.VITE_APP_BASE_URL),
    routes: systemRouter
})

// 扩展路由实例方法
extendRouter(router)

// 修改检查登录状态的函数
const checkLogin = async () => {
    try {
        const token = localStorage.getItem('token')
        if (!token) {
            return false
        }

        // 验证 token
        const response = await request.post('http://cylyxsz.w1.luyouxia.net/api/users/verify', {
            token: token
        }) as any
        console.log(response)
        return response.success
    } catch (error) {
        console.error('验证登录失败:', error)
        return false
    }
}

// 添加白名单路由列表
const whiteList = [
    '/login',
    '/home',
    '/tech',
    '/tech/',
    '/life',
    '/life/',
    '/about',
    '/guestbook',
    '/photos',
    '/code-generator',
    '/private',
    '/moments',
    '/docs'
]

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`

    // 检查当前路由是否在白名单中，或者是否匹配 /tech/:id 或 /life/:id 模式
    if (whiteList.includes(to.path) ||
        /^\/tech\/[^/]+$/.test(to.path) ||
        /^\/life\/[^/]+$/.test(to.path)) {
        next()
        return
    }

    // 验证登录状态
    const isLoggedIn = await checkLogin()

    if (isLoggedIn) {
        next()
    } else {
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    }
})

router.afterEach(() => {
    NProgress.done()
});

export async function setupRouter(app: App) {
    app.use(router)
}

export default router;
